//  Copyright (c) 2010, Keith Nixon, Sales Engineering, Salesforce.com Inc.
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
//  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//  Neither the name of the salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
//  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//  *NB - This is NOT a bulkified trigger
//
//  History
//
//  Version  Date            Author          Comments
//  1.0      19-01-2011      Keith Nixon     Initial version. Sets the completeness of an objective on the
//                                           associated outlet objective parent record.
//
//  ***** THIS IS NOT A BULK CONTRACT
//
trigger SetObjectiveCompletenessAfterUpdate on Outlet_Visit_Activity__c (after update) {
    // get list of objective activities.
    Outlet_Visit_Activity__c o = Trigger.new.get(0);
    Id objectiveId = [Select Objective__c From Objective_Activity__c Where Id =: o.Objective_Activity__c LIMIT 1].Objective__c;
    Id accId = [Select Outlet_Visits_LU__r.Account__c From Outlet_Visit_Activity__c Where Id=:o.Id LIMIT 1].Outlet_Visits_LU__r.Account__c;
    System.debug('\n\n***** ACCOUNT ID IS: ' + accId);
    System.debug('\n\n***** OBJECTIVE ID IS: ' + objectiveId);
    Map<Id,Boolean> objectiveActivitiesStatus = new Map<Id,Boolean>();
    Map<Id,Objective_Activity__c> objectiveActivitiesMap = new Map<Id,Objective_Activity__c>();
    
    if(objectiveId != null)
    {
        // get the objective activities and their child outlet visit activities for the relevant account.
        List<Objective_Activity__c> oa = [
            Select Name, Id, (Select Id, Name, Status__c From Outlet_Visit_Activity__r Where Outlet_Visits_LU__r.Account__c =: accId) From Objective_Activity__c
            Where Objective__c =: objectiveId
        ];
        
        System.debug('\n\n***** OBJECTIVE ACTIVITIES: ' + oa);
        
        //initialise the map
        for(Objective_Activity__c oact : oa)
        {
            objectiveActivitiesStatus.put(oact.Id,false);
            objectiveActivitiesMap.put(oact.Id,oact);
        }
        
        // check which activities are completed.
        for(Id objectiveActivityId : objectiveActivitiesStatus.keySet())
        {
            //check the visit activity for this objective activity
            for(Outlet_Visit_Activity__c ova : objectiveActivitiesMap.get(objectiveActivityId).Outlet_Visit_Activity__r)
            {
                if(ova.Status__c != null && ova.Status__c.equalsIgnoreCase('completed'))
                {
                    //means that this objective activity has been completed
                    //at some stage.
                    objectiveActivitiesStatus.put(objectiveActivityId, true);
                    break;
                }
                else continue;
            }
        }
        
        System.debug('\n\n***** OBJECTIVE ACTIVITY STATUSES: ' +  objectiveActivitiesStatus);
        
        //now check if all activities are completed
        Integer numCompleted = 0;
        for(Id objId : objectiveActivitiesStatus.keySet())
        {
            if(objectiveActivitiesStatus.get(objId))
            {
                numCompleted++;
            }
        }
        
        if(numCompleted == objectiveActivitiesStatus.size())
        {
            //means the objective is completed. set corresponding
            //outlet objective to 'completed'.
            System.debug('\n\n***** OBJECTIVE ACTIVITIES COMPLETED FOR: ' + objectiveId);
            
            //update the corresponding outlet objective.
            Outlet_Objectives__c oo = [
                Select Id, Name, Status__c From Outlet_Objectives__c Where Objective__c =: objectiveId AND Account__c =: accId LIMIT 1
            ];
            
            if(oo != null)
            {
                oo.Status__c = 'Completed';
                upsert oo;
            }
        }
    }
}